package com.syedu.day16;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;

/**
 * description：
 * @author Administrator
 * @date 2022/4/7 10:58
 */
public class ReaderDemo3 {
    public static void main(String[] args) {
        //registerUser("admin2", "654321");
        User user = loginUser("admin2", "654321");
        System.out.println(user);
    }

    /**
     * 注册方法
     */
    public static void registerUser(String username, String password) {
        String userStr = username + ":" + password + "\n";
        try {
            //开启写入追加模式
            Files.writeString(Path.of("user.txt"), userStr, StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录方法
     */
    public static User loginUser(String username, String password) {
        User user = null;
        try {
            List<String> stringList = Files.readAllLines(Path.of("user.txt"));
            for (String userStr : stringList) {
                String[] split = userStr.split(":");
                if (username.equals(split[0]) && password.equals(split[1])) {
                    user = new User(username, password);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return user;
    }
}